package com.alks.function.service.impl.procurement;

import com.alibaba.druid.util.StringUtils;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.procurement.ReviewMaterialDto;
import com.alks.function.data.request.procurement.ReviewMaterialRequest;
import com.alks.function.mapper.procurement.ReviewMaterialMapper;
import com.alks.function.service.procurement.ReviewMaterialService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ReviewMaterialServiceImpl implements ReviewMaterialService {

    @Autowired
    private ReviewMaterialMapper reviewMaterialMapper;

    /**
     * 评审资料查询
     *
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getReviewMaterialList(ReviewMaterialRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        //复合查询
        List<ReviewMaterialDto> reviewMaterialList = reviewMaterialMapper.getReviewMaterialList(request);

        PageInfo list = new PageInfo(reviewMaterialList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", reviewMaterialList);
        map.put("total", list.getTotal());

        return ResponseInfo.ok(map);
    }

    /**
     * 更新指令
     *
     * @param request
     * @return
     */
    @Override
    public ResponseInfo reviewMaterialUpdate(List<ReviewMaterialRequest> request) {
        if (ObjectUtils.isEmpty(request)) {
            throw new ServiceErrorException("指令不能为空!");
        }

        //ReviewMaterialDto reviewMaterialDto = new ReviewMaterialDto();
        //BeanUtil.copyProperties(request, reviewMaterialDto);
        //reviewMaterialMapper.reviewMaterialUpdate(reviewMaterialDto);

        //创建新集合
        String companyId = UserIdThread.get().getCompanyId();
        List<ReviewMaterialDto> reviewMaterialDtos = new ArrayList<>();
        for (ReviewMaterialRequest r : request) {
            ReviewMaterialDto reviewMaterialDto = new ReviewMaterialDto();
            BeanUtil.copyProperties(r, reviewMaterialDto);
            reviewMaterialDto.setCompanyId(companyId);
            reviewMaterialDtos.add(reviewMaterialDto);
        }

        //批量更新
        reviewMaterialMapper.batchUpdateReviewMaterial(reviewMaterialDtos);

        return ResponseInfo.ok("更新指令成功！");
    }

    /**
     * 更新指令（按钮）
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo reviewMaterialAdd() {
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        LocalDate now = LocalDate.now();
        //直接查询评审资料上没有的指令数据
        List<ReviewMaterialDto> reviewMaterialDtos = reviewMaterialMapper.getLotNoList(companyId);

        if(reviewMaterialDtos.size() == 0){
            throw new ServiceErrorException("没有需要更新的指令！");
        }
        //批量新增
        int count = reviewMaterialMapper.addBatchReviewMaterial(reviewMaterialDtos, now, companyId, userName);
        if(count > 0 ){
            return ResponseInfo.ok("抓取指令成功！");
        }else{
            throw new ServiceErrorException("抓取指令失败！");
        }
    }

    /**
     * 勾选复制
     * 就是把我选中行批量复制给勾选的数据行
     *
     * @param lotNos
     * @param lotNo
     * @return
     */
    @Override
    public ResponseInfo selectAndCopy(List<String> lotNos, String lotNo) {
        //我选中的指令行
        ReviewMaterialDto reviewMaterialDto = reviewMaterialMapper.getReviewMaterialByLotNo(lotNo);
        if (reviewMaterialDto != null) {
            //取出要复制的值
            double u = reviewMaterialDto.getUpperMtlLt();
            double s = reviewMaterialDto.getSoleMtlLt();
            double smd = reviewMaterialDto.getSoleMoldLt();
            double hf = reviewMaterialDto.getHfLt();
            double st = reviewMaterialDto.getStitchPpd();
            double lp = reviewMaterialDto.getLastPpd();

            //勾选的指令行
            List<ReviewMaterialDto> reviewMaterialDtoList = reviewMaterialMapper.getReviewMaterialByLotNos(lotNos);
            if (ObjectUtils.isNotEmpty(reviewMaterialDtoList)) {

                // 批量更新操作
                List<ReviewMaterialDto> updatedDtoList = reviewMaterialDtoList.stream().map(r -> {
                    r.setUpperMtlLt(u);
                    r.setSoleMtlLt(s);
                    r.setSoleMoldLt(smd);
                    r.setHfLt(hf);
                    r.setStitchPpd(st);
                    r.setLastPpd(lp);
                    return r;
                }).collect(Collectors.toList());

                // 执行批量更新
                reviewMaterialMapper.batchUpdateReviewMaterial(updatedDtoList);
                return ResponseInfo.ok("复制成功！");
            }
        }
        throw new ServiceErrorException("指令不存在!");
    }

    /**
     * 评审资料添加
     *
     * @param request
     * @return
     */
    @Override
    public ResponseInfo addReviewMaterial(ReviewMaterialRequest request) {
        if (StringUtils.isEmpty(request.getLotNo())) {
            throw new ServiceErrorException("指令不能为空!");
        }

        if (reviewMaterialMapper.getReviewMaterialByLotNo(request.getLotNo()) != null) {
            throw new ServiceErrorException("该指令已存在,不能添加!");
        }

        //取到用户
        SysUserTokenDTO sysUserTokenDTO = UserIdThread.get();
        String userName = sysUserTokenDTO.getUserName();
        String companyId = UserIdThread.get().getCompanyId();

        //拷贝赋值
        ReviewMaterialDto reviewMaterialDto = new ReviewMaterialDto();
        BeanUtil.copyProperties(request, reviewMaterialDto);
        reviewMaterialDto.setSysUser(userName);
        reviewMaterialDto.setCompanyId(companyId);
        reviewMaterialDto.setSysDate(new Date());

        //添加
        reviewMaterialMapper.addReviewMaterial(reviewMaterialDto);

        return ResponseInfo.ok("添加成功！");

    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
    @Override
    public ResponseInfo deleteReviewMaterial(ReviewMaterialRequest request) {
        String lotNo = request.getLotNo();
        String companyId = UserIdThread.get().getCompanyId();
        if (StringUtils.isEmpty(lotNo)) {
            throw new ServiceErrorException("指令不能为空!");
        }

        if (reviewMaterialMapper.getReviewMaterialByLotNo(request.getLotNo()) == null) {
            throw new ServiceErrorException("该指令不存在,无法删除!");
        }

        reviewMaterialMapper.deleteReviewMaterial(lotNo,companyId);
        return ResponseInfo.ok("删除成功！");

    }

    /**
     * 导出
     * @param lotNoList
     * @param response
     */
    @Override
    public void exportReviewMaterial(List<String> lotNoList, HttpServletResponse response) throws IOException {
//        String fileName = "订单评审资料_" + DateUtils.dateTimeNow() + ".xlsx";
        String companyId = UserIdThread.get().getCompanyId();
        List<ReviewMaterialDto> list =  reviewMaterialMapper.queryExportReviewMaterial(companyId, lotNoList);
        ExcelUtils.creatByTemplate(response,"订单评审资料模板.xls","评审资料_"+DateUtils.dateTimeNow(),list);
    }

}

